//
//  YHGroupInviteViewController.m
//  HYChatProject
//  选择群成员
//  Created by jagtu on 16/5/16.
//  Copyright © 2018年 jt. All rights reserved.
//

#import "YHGroupInviteViewController.h"
#import "HYForwardingViewCell.h"
#import "HYContactsModel.h"
#import "HYXMPPManager.h"
#import "HYXMPPGroupManager.h"
#import "XMPPUserCoreDataStorageObject.h"
#import "HYUtils.h"
#import "HYAddFriendViewController.h"
#import "APGroupImageUtil.h"
#import "HYLoginInfo.h"

#define kFooterHeight 49.0
static NSString *kForwardingViewCellIdentifier = @"kForwardingViewCellIdentifier";
static NSString *kForwardingHeaderViewIdentifier = @"kForwardingHeaderViewIdentifier";
static NSString *kForwardingIconViewCellIdentifier = @"kForwardingIconViewCellIdentifier";

@interface YHGroupInviteViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray * selectedMembersImages;
@end

@implementation YHGroupInviteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = APP_ViewBg_COLOR;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    
    // Do any additional setup after loading the view.
    self.title = @"选择群成员";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[HYForwardingViewCell class] forCellReuseIdentifier:kForwardingViewCellIdentifier];
    [self.view addSubview:self.tableView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick:)];
    [self setupFooterView]; // UI
    [self setupDataSource];  // 数据
    if(self.isRemove){
        self.title = @"删除群成员";
    }
    
    if (!self.vCard) {
        
        __weak typeof(self) weakSelf = self;
        [[HYXMPPManager sharedInstance] getvCardFromJID:self.groupJid vCardBlock:^(XMPPvCardTemp *vCardTemp) {
            // 获取名片
            __strong typeof(weakSelf) strongSellf = weakSelf;
            strongSellf.vCard = vCardTemp;
        }];
        
    }
}

- (void)setupDataSource
{
    self.selectedMembersImages = [NSMutableArray array];
    
    if (self.isRemove) {
        [self.dataSource removeAllObjects];
        for (HYContactsModel *s_model in self.selectedArray) {
            if (![[HYXMPPManager sharedInstance].myJID.bare isEqualToString:s_model.jid.bare]) {
                [self.dataSource addObject:s_model];
            }
        }
        
        //
        
    }else{
        
        // 2.联系人   XMPPRoster.xcdatamodel
        NSManagedObjectContext *context = [[HYXMPPManager sharedInstance] managedObjectContext_roster];
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];
        NSPredicate *pre=[NSPredicate predicateWithFormat:@"streamBareJidStr == %@",[HYXMPPManager sharedInstance].myJID.bare];
        fetchRequest.predicate=pre; // 过滤
        NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
        fetchRequest.sortDescriptors=@[sort]; // 排序
        NSError *error;
        NSArray *fetchObjects = [context executeFetchRequest:fetchRequest error:&error];
        
        [self.dataSource removeAllObjects];
        
        [fetchObjects enumerateObjectsUsingBlock:^(XMPPUserCoreDataStorageObject *object, NSUInteger idx, BOOL * _Nonnull stop) {
            HYContactsModel *model = [[HYContactsModel alloc] init];
            model.jid = object.jid;
            model.nickName = object.nickname.length ? object.nickname : object.jid.user;
            model.sectionNum = 0;
            model.isGroup = NO;
            for (HYContactsModel *s_model in self.selectedArray) {
                if ([model.jid.bare isEqualToString:s_model.jid.bare]) {
                    model.sectionNum = 1;
                    break;
                }else if ([[HYXMPPManager sharedInstance].myJID.bare isEqualToString:s_model.jid.bare]) {
                    [self.dataSource removeObject:s_model];
                }
            }
            if (model.sectionNum == 0) {
                if (![model.jid.user isEqualToString:[HYLoginInfo sharedInstance].superior]
                    &&
                    ![model.nickName hasPrefix:@"#C_"])
                {
                    //上级，排除掉
                    [self.dataSource addObject:model];
                }
            }
        }];
    }
}

- (void)setupFooterView
{
    // 1.底部view
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - kFooterHeight, CGRectGetWidth(self.view.bounds), kFooterHeight)];
    self.footerView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0f];
    [self.view addSubview:self.footerView];
    
    // 2.线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.footerView.bounds), 1)];
    line.backgroundColor = [UIColor colorWithRed:222/255.0f green:222/255.0f blue:222/255.0f alpha:1.0f];
    [self.footerView addSubview:line];
    
    // 3.发送
    CGFloat buttonWidth = 64;
    CGFloat buttonX = CGRectGetWidth(self.footerView.bounds) - buttonWidth;
    self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(buttonX, 1, buttonWidth, kFooterHeight - 1)];
    [self.sendButton setTitle:@"完成" forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor colorWithRed:50/255.0 green:155/255.0 blue:250/255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.footerView addSubview:self.sendButton];
    
    // 4.1.流水布局
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kFooterHeight - 1, kFooterHeight - 1);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    // 4.2.实例化collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 1, buttonX - 10, kFooterHeight - 1) collectionViewLayout:layout];
    // 4.3.注册cell(告诉collectionView将来创建怎样的cell)
    [self.collectionView registerClass:[HYForwardingIconViewCell class] forCellWithReuseIdentifier:kForwardingIconViewCellIdentifier];
    // 4.4.设置背景色和代理
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.footerView addSubview:self.collectionView];
}


#pragma mark - UITableViewDatasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYContactsModel *chatModel = [self.dataSource objectAtIndex:indexPath.row];
    HYForwardingViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kForwardingViewCellIdentifier];
    if (self.isRemove) {
        cell.accessoryType = chatModel.sectionNum ? UITableViewCellAccessoryNone :UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = chatModel.sectionNum ? UITableViewCellAccessoryCheckmark :UITableViewCellAccessoryNone;
    }
    cell.chatModel = chatModel;
    
    if (self.isRemove) {
        [self.selectedMembersImages addObject:cell.headView.image];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    HYForwardingHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kForwardingHeaderViewIdentifier];
    if (headerView == nil) {
        headerView = [[HYForwardingHeaderView alloc] initWithReuseIdentifier:kForwardingHeaderViewIdentifier];
    }
    headerView.titleLabel.text = @"好友";
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kForwardingHeaderViewHeight;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    HYContactsModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if (model.sectionNum == 0) {
        model.sectionNum = 1;
        [self.selectedArray insertObject:model atIndex:0];
        [self.unSelectedArray removeObject:model];
        
    } else {
        model.sectionNum = 0;
        [self.selectedArray removeObject:model];
        [self.unSelectedArray insertObject:model atIndex:0];
        
    }
    if (!self.isRemove) {
        [self.selectedMembersImages removeAllObjects];
    }
    [self.collectionView reloadData];
    
    [UIView performWithoutAnimation:^{
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }];
}



#pragma mark - UICollectionView dataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.isRemove) {
        return self.unSelectedArray.count;
    }
    return self.selectedArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HYForwardingIconViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kForwardingIconViewCellIdentifier forIndexPath:indexPath];
    HYContactsModel *chatModel = nil;
    if (self.isRemove) {
        chatModel =  [self.unSelectedArray objectAtIndex:indexPath.row];
    }else{
        chatModel = [self.selectedArray objectAtIndex:indexPath.row];
    }
    cell.chatModel = chatModel;
    if (self.isRemove) {
        [self.selectedMembersImages addObject:cell.headView.image];
    }
    return cell;
}

/**
 *  取消发送
 */
- (void)cancelClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  发送
 */

- (void)sendButtonClick:(id)sender
{
    if (self.selectedArray.count == 0 && !self.isRemove) {
        [HYUtils alertWithNormalMsg:@"请选择群成员!"];
        return;
    }
    
    
    
    if (self.isRemove) {
        
        NSString * message = [NSString stringWithFormat:@"将删除%ld位成员，是否确定？",self.unSelectedArray.count];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"删除成员" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            [HYUtils showWaitingMsg:@"加载中.."];
            
            YHWeakifySelf;
            [[HYXMPPGroupManager sharedInstance] leaveMembers:self.unSelectedArray inGroupJID:self.groupJid success:^(BOOL success) {
                YHStrongifySelf;
                if (success) {
                    [HYUtils alertWithSuccessMsg:@"设置成功！"];
                    [self generateHeadImage];
                    
                    [self back:nil];
                    
                }else{
                    [HYUtils alertWithSuccessMsg:@"设置失败，请重试！"];
                }
            }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }
    [HYUtils showWaitingMsg:@"加载中.."];
    YHWeakifySelf;
    [[HYXMPPGroupManager sharedInstance] joinGroupWithGroupJID:self.groupJid withMembers:self.selectedArray success:^(BOOL success) {
        YHStrongifySelf;
        if (success) {
            [HYUtils alertWithSuccessMsg:@"设置成功！"];
            
            [self generateHeadImage];
            
            [self back:nil];
            
        }else{
            [HYUtils alertWithSuccessMsg:@"设置失败，请重试！"];
        }
    }];
}

//生产群头像
-(void)generateHeadImage
{
    UIImage *img = [[APGroupImageUtil shared] mergeWithImageArray:self.selectedMembersImages size:CGSizeMake(100, 100) backgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]];
    
    if (img) {
        NSLog(@"----666-save 群头像ing----");
        [[HYXMPPManager sharedInstance] updatevCardFromJID:self.groupJid vCard:self.vCard successBlock:^(BOOL success) {
            NSLog(@"----666----");
        }];
    }
}


#pragma mark - 懒加载

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kFooterHeight)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = kForwardingViewCellHeight;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

// 懒加载
- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)selectedArray
{
    if (_selectedArray == nil) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}

- (NSMutableArray *)unSelectedArray
{
    if (_unSelectedArray == nil) {
        _unSelectedArray = [NSMutableArray array];
    }
    return _unSelectedArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)back:(id)sender
{
    if (self.groupMembersBlock) {
        self.groupMembersBlock(self.selectedArray);
    }
    NSArray * vcs = self.navigationController.viewControllers;
    if (vcs.count > 2 && [[vcs objectAtIndex:vcs.count-2] isKindOfClass:[HYAddFriendViewController class]]) {
        //上一个页面是HYAddFriendViewController
        [self.navigationController popToViewController:[vcs objectAtIndex:vcs.count-3] animated:YES];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
